<?php
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];
    if (strlen($username) > 191) {
        echo "<script>alert('用户名不能超过191个字符！');</script>";
    } else {
        $stmt = $conn->prepare("SELECT id, password, role FROM users WHERE username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($user = $result->fetch_assoc()) {
            if (password_verify($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['role'] = $user['role'];
                session_regenerate_id(true);
                $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
                header("Location: index.php");
                exit;
            } else {
                echo "<script>alert('密码验证失败！');</script>";
            }
        } else {
            echo "<script>alert('用户名不存在！');</script>";
        }
    }
}

$settings = file_exists(__DIR__ . '/settings.json') ? json_decode(file_get_contents(__DIR__ . '/settings.json'), true) : ['title' => '私人网盘'];
$site_title = $settings['title'];
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录 - <?= htmlspecialchars($site_title) ?></title>
    <link href="/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="<?= $settings['theme'] === 'dark' ? 'bg-dark text-white' : '' ?>">
    <div class="container py-5">
        <h2>登录</h2>
        <form method="POST">
            <div class="mb-3">
                <label for="username" class="form-label">用户名</label>
                <input type="text" class="form-control" id="username" name="username" maxlength="191" required>
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">密码</label>
                <input type="password" class="form-control" id="password" name="password" required>
            </div>
            <button type="submit" class="btn btn-primary">登录</button>
        </form>
    </div>
    <script src="/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>